package qsh.laputa.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.Map;
import java.util.Set;

/**
 * <p>
 *
 * </p>
 *
 * @author Qsh
 * @since 2021/3/17
 */
public class QueryUtil {

    /**
     * 构建MyQuery对象，服务于分页查询方法
     *
     * @param params
     * @param <T>
     * @return
     */
    public static <T> MyQuery<T> buildMyQuery(Map<String, String> params) {
        MyQuery<T> myQuery = new MyQuery<>();
        QueryWrapper<T> wrapper = new QueryWrapper<>();

        long page = 1L;
        long limit = 10L;

        Set<Map.Entry<String, String>> entries = params.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String value = entry.getValue();
            if (StringUtils.isNotBlank(value)) {
                String key = entry.getKey();
                if ("page".equals(key)) {
                    page = Long.parseLong(value);
                } else if ("limit".equals(key)) {
                    limit = Long.parseLong(value);
                } else {
                    String[] keyArray = key.split("\\$");   //以$进行分割
                    String param = StringUtils.camelToUnderline(keyArray[1]);
                    switch (keyArray[0]) {
                        case "like":
                            wrapper.like(param, value);
                            break;
                        case "ge":
                            wrapper.ge(param, value);
                            break;
                        case "le":
                            wrapper.le(param, value);
                            break;
                        case "eq":
                            wrapper.eq(param, value);
                            break;
                        case "range":
                            String[] timeArray = value.split(" - ");
                            wrapper.ge(param, timeArray[0])
                                    .le(param, timeArray[1]);
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        myQuery.setPage(new Page<>(page, limit));
        myQuery.setWrapper(wrapper);
        return myQuery;
    }
}
